import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Auths, Role } from '@/utils/types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { useRef, useState } from 'react';
import { useModel } from 'umi';
import { queryShiftConfigs, removeShiftConfig } from '../service';
import { ShiftConfigTableItem } from '../types.d';
import CreateShiftConfig from './components/CreateShiftConfig';
import UpdateShiftConfig from './components/UpdateShiftConfig';

const padZero = (n: number) => String(n).padStart(2, '0');
const ShiftConfigList = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.scheduleManagement || []) : new Set();

  const ifDelete = auths.has(Auths.DELETE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifCreate = auths.has(Auths.CREATE);

  const [modifyVisible, setModifyVisible] = useState<boolean>(false);
  const [currItem, setCurrItem] = useState<ShiftConfigTableItem>();

  const columns: ProColumns<ShiftConfigTableItem>[] = [
    {
      title: 'id',
      hideInTable: true,
      hideInSearch: true,
      dataIndex: '_id',
    },
    {
      title: '归属公司',
      dataIndex: 'ownerId',
      hideInForm: true,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      fieldProps: { showSearch: true },
      render: (_, record) => record.ownerInfo?.ownerName || record.ownerId,
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
    },
    {
      title: '班次名称',
      dataIndex: 'name',
      hideInForm: true,
      align: 'center',
    },
    {
      title: '时间区间',
      dataIndex: 'timeFrames',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
      renderText: (_, record) => {
        if (!record.timeFrames || record.timeFrames.length != 2) return '暂无数据';
        const [start, end] = record.timeFrames;
        const startH = Math.floor(start / 60);
        const startM = start % 60;
        const endH = Math.floor(end / 60);
        const endM = end % 60;
        return `${padZero(startH)}:${padZero(startM)} - ${padZero(endH)}:${padZero(endM)}`;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
      align: 'center',
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (_, record, x, action) => {
        if (!ifDelete && !ifModify) return [<PlaceHolderCpn />];
        return [
          ifModify && (
            <a
              key={`modify_${record._id}`}
              onClick={() => {
                setCurrItem(record);
                setModifyVisible(true);
              }}
            >
              修改
            </a>
          ),
          ifDelete && (
            <ConfirmModal
              reload={() => action?.reload()}
              operFunc={async () => await removeShiftConfig(record._id)}
              text={`是否确定要删除班次「${record.name}」`}
            />
          ),
        ];
      },
    },
  ];

  const actionRef = useRef<ActionType>();

  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '收费人员班次配置管理列表',
        breadcrumb: {
          routes: [
            {
              path: '/',
              breadcrumbName: '首页',
            },
            {
              path: '/staff',
              breadcrumbName: '员工管理',
            },
            {
              path: '/staff/schedule',
              breadcrumbName: '班次配置',
            },
          ],
        },
      }}
    >
      <ProTable<ShiftConfigTableItem>
        columns={columns}
        search={{ labelWidth: 'auto' }}
        style={{ whiteSpace: 'nowrap' }}
        rowKey="_id"
        actionRef={actionRef}
        columnEmptyText="暂无数据"
        dateFormatter="string"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryShiftConfigs(param, sort);
          return res;
        }}
        toolBarRender={(action) => [
          ifCreate && <CreateShiftConfig key="create_shift" reload={() => action?.reload()} />,
        ]}
      />
      {ifModify && modifyVisible && currItem && (
        <UpdateShiftConfig
          visible={modifyVisible}
          currItem={currItem}
          setUnvisible={() => {
            setCurrItem(undefined);
            setModifyVisible(false);
          }}
          reload={() => {
            actionRef.current?.reload();
          }}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default ShiftConfigList;
